"use client"

import { useState, useEffect } from 'react'
import { getPlayers, getRegions } from '@/lib/data'
import { Player, Region } from '@/types/player'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Skeleton } from '@/components/ui/skeleton'
import { Bar, BarChart, ResponsiveContainer, XAxis, YAxis, Tooltip } from 'recharts'
import { Users, Map, Medal, Award, TrendingUp, AlertTriangle } from 'lucide-react'

export default function AdminDashboard() {
  const [players, setPlayers] = useState<Player[]>([])
  const [regions, setRegions] = useState<Region[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [stats, setStats] = useState({
    totalPlayers: 0,
    totalRegions: 0,
    averageScore: 0,
    playersByRegion: [] as {name: string, count: number}[],
    playersByTier: [] as {name: string, count: number}[],
    recentActivity: 5,
    blacklistedPlayers: 0
  })

  useEffect(() => {
    async function loadData() {
      try {
        setLoading(true)
        setError(null)
        
        // 并行加载数据
        const [playersData, regionsData] = await Promise.all([
          getPlayers(),
          getRegions()
        ])
        
        setPlayers(playersData)
        setRegions(regionsData)
        
        // 计算统计数据
        calculateStats(playersData, regionsData)
      } catch (err: any) {
        console.error('加载数据失败:', err)
        setError('无法加载仪表盘数据，请稍后重试')
      } finally {
        setLoading(false)
      }
    }
    
    loadData()
  }, [])
  
  const calculateStats = (players: Player[], regions: Region[]) => {
    // 总玩家数
    const totalPlayers = players.length
    
    // 总地区数
    const totalRegions = regions.length
    
    // 平均分数
    const totalScore = players.reduce((sum, player) => sum + (player.score || 0), 0)
    const averageScore = totalPlayers > 0 ? Math.round(totalScore / totalPlayers) : 0
    
    // 按地区统计玩家数
    const playersByRegion = regions.map(region => {
      const count = players.filter(player => player.region === region.name).length
      return {
        name: region.name,
        count,
        color: region.color
      }
    }).sort((a, b) => b.count - a.count)
    
    // 按段位统计玩家数
    const tierCounts: Record<string, number> = {}
    players.forEach(player => {
      if (player.best_tier_name) {
        tierCounts[player.best_tier_name] = (tierCounts[player.best_tier_name] || 0) + 1
      }
    })
    
    const playersByTier = Object.entries(tierCounts)
      .map(([name, count]) => ({ name, count }))
      .sort((a, b) => b.count - a.count)
    
    // 黑名单玩家数
    const blacklistedPlayers = players.filter(player => player.is_blacklisted).length
    
    setStats({
      totalPlayers,
      totalRegions,
      averageScore,
      playersByRegion,
      playersByTier,
      recentActivity: 5, // 模拟数据
      blacklistedPlayers
    })
  }

  if (loading) {
    return <DashboardSkeleton />
  }

  if (error) {
    return (
      <div className="p-4 rounded-lg bg-red-950 border border-red-800 text-red-200 mb-6">
        <div className="flex items-center gap-2 mb-2">
          <AlertTriangle className="h-5 w-5" />
          <h3 className="font-semibold">加载错误</h3>
        </div>
        <p>{error}</p>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      <h2 className="text-2xl font-bold tracking-tight">仪表盘</h2>
      
      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        <StatCard 
          title="总玩家数" 
          value={stats.totalPlayers.toString()} 
          description="系统中的注册玩家"
          icon={<Users className="h-5 w-5" />}
          trend={+5}
          color="blue"
        />
        
        <StatCard 
          title="地区数量" 
          value={stats.totalRegions.toString()} 
          description="已配置的玩家地区"
          icon={<Map className="h-5 w-5" />}
          color="green"
        />
        
        <StatCard 
          title="平均分数" 
          value={stats.averageScore.toString()} 
          description="所有玩家的平均分"
          icon={<Award className="h-5 w-5" />}
          trend={+3}
          color="yellow"
        />
        
        <StatCard 
          title="黑名单玩家" 
          value={stats.blacklistedPlayers.toString()} 
          description="被限制的玩家账号"
          icon={<AlertTriangle className="h-5 w-5" />}
          color="red"
        />
      </div>
      
      {/* 图表区域 */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* 地区分布图表 */}
        <Card className="border border-gray-800 bg-[#1a1d24]">
          <CardHeader>
            <CardTitle>玩家地区分布</CardTitle>
            <CardDescription>按地区统计的玩家数量</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="h-80">
              <ResponsiveContainer width="100%" height="100%">
                <BarChart data={stats.playersByRegion.slice(0, 8)}>
                  <XAxis 
                    dataKey="name" 
                    stroke="#888888" 
                    fontSize={12}
                    tickLine={false}
                    axisLine={false}
                  />
                  <YAxis 
                    stroke="#888888"
                    fontSize={12}
                    tickLine={false}
                    axisLine={false}
                    tickFormatter={(value) => `${value}`}
                  />
                  <Tooltip
                    contentStyle={{
                      backgroundColor: '#1a1d24',
                      border: '1px solid #2d3748',
                      borderRadius: '0.5rem',
                      color: 'white',
                    }}
                  />
                  <Bar 
                    dataKey="count" 
                    radius={[4, 4, 0, 0]}
                    fill="#3b82f6"
                  />
                </BarChart>
              </ResponsiveContainer>
            </div>
          </CardContent>
        </Card>
        
        {/* 段位分布图表 */}
        <Card className="border border-gray-800 bg-[#1a1d24]">
          <CardHeader>
            <CardTitle>段位分布统计</CardTitle>
            <CardDescription>按段位统计的玩家数量</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="h-80">
              <ResponsiveContainer width="100%" height="100%">
                <BarChart data={stats.playersByTier.slice(0, 8)}>
                  <XAxis 
                    dataKey="name" 
                    stroke="#888888" 
                    fontSize={12}
                    tickLine={false}
                    axisLine={false}
                  />
                  <YAxis 
                    stroke="#888888"
                    fontSize={12}
                    tickLine={false}
                    axisLine={false}
                    tickFormatter={(value) => `${value}`}
                  />
                  <Tooltip
                    contentStyle={{
                      backgroundColor: '#1a1d24',
                      border: '1px solid #2d3748',
                      borderRadius: '0.5rem',
                      color: 'white',
                    }}
                  />
                  <Bar 
                    dataKey="count" 
                    radius={[4, 4, 0, 0]}
                    fill="#f59e0b"
                  />
                </BarChart>
              </ResponsiveContainer>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}

// 统计卡片组件
function StatCard({ 
  title, 
  value, 
  description, 
  icon, 
  trend, 
  color 
}: { 
  title: string, 
  value: string, 
  description: string, 
  icon: React.ReactNode, 
  trend?: number,
  color: 'blue' | 'green' | 'yellow' | 'red'
}) {
  const colorMap = {
    blue: "bg-blue-950/30 border-blue-900 text-blue-500",
    green: "bg-green-950/30 border-green-900 text-green-500",
    yellow: "bg-yellow-950/30 border-yellow-900 text-yellow-500",
    red: "bg-red-950/30 border-red-900 text-red-500",
  }
  
  return (
    <Card className={`border ${colorMap[color]} bg-[#1a1d24]`}>
      <CardHeader className="flex flex-row items-center justify-between pb-2">
        <CardTitle className="text-sm font-medium text-gray-200">{title}</CardTitle>
        <div className={`p-2 rounded-full ${colorMap[color].split(' ')[0]}`}>
          {icon}
        </div>
      </CardHeader>
      <CardContent>
        <div className="text-2xl font-bold">{value}</div>
        <p className="text-xs text-gray-400 mt-1">{description}</p>
        {trend !== undefined && (
          <div className="flex items-center mt-2">
            <TrendingUp className={`h-4 w-4 mr-1 ${trend >= 0 ? 'text-green-500' : 'text-red-500'}`} />
            <span className={`text-xs ${trend >= 0 ? 'text-green-500' : 'text-red-500'}`}>
              {trend >= 0 ? '+' : ''}{trend}% 较上月
            </span>
          </div>
        )}
      </CardContent>
    </Card>
  )
}

// 仪表盘骨架屏
function DashboardSkeleton() {
  return (
    <div className="space-y-6">
      <Skeleton className="h-8 w-36" />
      
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        {[1, 2, 3, 4].map(i => (
          <Card key={i} className="border border-gray-800 bg-[#1a1d24]">
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <Skeleton className="h-4 w-24" />
              <Skeleton className="h-10 w-10 rounded-full" />
            </CardHeader>
            <CardContent>
              <Skeleton className="h-8 w-16 mb-2" />
              <Skeleton className="h-3 w-full" />
            </CardContent>
          </Card>
        ))}
      </div>
      
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {[1, 2].map(i => (
          <Card key={i} className="border border-gray-800 bg-[#1a1d24]">
            <CardHeader>
              <Skeleton className="h-6 w-36 mb-2" />
              <Skeleton className="h-4 w-48" />
            </CardHeader>
            <CardContent>
              <Skeleton className="h-80 w-full" />
            </CardContent>
          </Card>
        ))}
      </div>
    </div>
  )
} 